﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;
namespace ET.Score.SharedLibrary
{
    public class JsonConvert<T>
    {
        public static void  DeepCopyObj(T srcobj,ref T desobj)
        {
            string s = ObjectToJson(srcobj);
            desobj = JsonToObject(s);
        }
        public static string ObjectToJson(T obj)
        {
            try
            {
                var serializer = new DataContractJsonSerializer(typeof(T));
                var stream = new MemoryStream();
                serializer.WriteObject(stream, obj);

                byte[] dataBytes = new byte[stream.Length];

                stream.Position = 0;

                stream.Read(dataBytes, 0, (int)stream.Length);

                string json = Encoding.UTF8.GetString(dataBytes);

                return json;
            }
            catch (Exception ex)
            {
                return "JSON_ERROR";
            }
        }

        public static T JsonToObject(string jsonString)
        {
            try
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
                T t1 = (T)serializer.ReadObject(stream);

                return t1;
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }

    }  
}
